import store from "./store.js"
// let ENV = 'http://192.168.10.124:8080' //本地
let ENV = 'https://jp.examss.cn/web' //建培圈正式
let timeHandle = null

function request(url, data = {}, option = {}) {
	let token = uni.getStorageSync('token') || '';
	let {
		loading = true, toast = true, method = 'get'
	} = option;
	let contentType = option.contentType ? option.contentType : 'application/json'
	let isFile = option.isFile
	return new Promise((resolve, reject) => {
		showLoading(loading)
		//延迟
		let getcompelete = null
		let requestData = {
			url: ENV + url,
			data,
			method,
			timeout: 20000,
			header: {
				'Content-type': contentType,
				'session-key': token,
			},
			success: function(result) {
				getcompelete = result
				let res = result.data;
				if (isFile) {
					res = JSON.parse(result.data)
				}
				if (res.code == 200) {
					if (loading) {
						uni.hideLoading();
						loading = false
					}
					resolve(res);
				} else {
					if (loading) {
						uni.hideLoading();
						loading = false
					}
					if (option.failHandle) {
						option.failHandle(res);
						return;
					}

					uni.showToast({
						mask: true,
						title: res.msg,
						duration: 1200,
						icon: 'none'
					})
					// 登录失效退回首页
					if (res.code == 401) {
						uni.clearStorageSync();
						uni.$u.route({
							type: 'redirect',
							url: '/pages/login/login'
						})
					}
				}
			},
			fail: function(e = {
				code: -1,
				msg: errMsg,
				errMsg
			}) {
				getcompelete = e
				uni.hideLoading();
				loading = false
				// console.log(e)
				let msg = e.errMsg;
				if (msg == "request:fail timeout") {
					msg = "请求超时，请稍后再试";
				} else if (msg == "request:fail" || msg == "") {
					msg = "请求失败,请检查网络环境"
				}
				uni.showToast({
					title: msg,
					icon: "none"
				})
				reject(e);
			}
		}
		if (!isFile) {
			uni.request(requestData)
		} else {
			let fileReqData = {}
			fileReqData.filePath = data.filePath //文件路径
			fileReqData.url = requestData.url
			fileReqData.name = 'file'
			fileReqData.header = {
				'session-key': token
			}
			fileReqData.success = requestData.success
			fileReqData.fail = requestData.fail
			uni.uploadFile(fileReqData)
		}

		if (timeHandle) {
			clearTimeout(timeHandle);
			timeHandle = null;
		}
		timeHandle = setTimeout(() => {
			// console.log(getcompelete, 'getcompelete', loading)
			if (loading) {
				uni.hideLoading();
				uni.showToast({
					title: '请求超时，请稍后再试',
					icon: "none"
				})
			}
		}, 20000)
	})
}

function showLoading(loading) {
	if (loading) {
		uni.showLoading({
			title: "加载中...",
			mask: true
		})
	}
}

export default request

export function getProjectCode() {
	return ENV === 'https://xxxxx/web/' ? 'ZJXT' : 'JPQ'
}

export function getProjectName() {
	return getProjectCode() == 'xxxxx'
}